package com.pa.utils;

import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.ProgressMonitor;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;

import java.io.File;
import java.io.IOException;

/**
 * @author 郑永震
 * @date 2021/8/25 0025 11:27
 * @mail zheng_yzh@163.com
 * @description 仓库相关
 */
public class RepositoryRelative {

    /**
     * 根据仓库路径生成新的存储库
     *
     * @param gitRepoPath 仓库路径
     * @return 存储库
     * @throws IOException IO异常
     */
    public static Repository configRepository(String gitRepoPath) throws IOException {
        //File repoDir = OpenRepository.createGitRepo(gitRepoPath);//这里其实不用创建新的仓库文件，直接创建文件，
        // 然后builder的时候录入文件路径信息就可以了
        File repoDir = new File(gitRepoPath);
        FileRepositoryBuilder builder = new FileRepositoryBuilder();
        return builder.setGitDir(repoDir).readEnvironment().findGitDir().build();
    }

    /**
     * @param gitRepoPath git文件路径
     * @return 存储库
     * @throws IOException IO异常
     */
    public static Repository createNewRepository(String gitRepoPath) throws IOException {
        File localPath = new File(gitRepoPath);
        return FileRepositoryBuilder.create(localPath);
    }

    /**
     * @param gitRepoPath 路径地址
     * @return 仓库文件
     * @throws IOException     IO异常
     */
    public static File createGitRepo(String gitRepoPath) throws IOException{
        try (Repository repository = createNewRepository(gitRepoPath)) {
            return repository.getDirectory();
        }
    }
    public static Repository getGitClone(File localPath, String url) throws IOException, GitAPIException {
        Git result = Git.cloneRepository()
                .setURI(url)
                .setDirectory(localPath)
                .setProgressMonitor(new SimpleProgressMonitor())
                .call();
        return result.getRepository();
    }

    private static class SimpleProgressMonitor implements ProgressMonitor{
        @Override
        public void start(int totalTasks) {
            System.out.println("Starting work on " + totalTasks + " tasks");
        }

        @Override
        public void beginTask(String title, int totalWork) {
            System.out.println("Start " + title + ": " + totalWork);
        }

        @Override
        public void update(int completed) {
            System.out.print(completed + "-");
        }

        @Override
        public void endTask() {
            System.out.println("Done");
        }

        @Override
        public boolean isCancelled() {
            return false;
        }
    }
}
